package com.csp.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {

    @RequestMapping("/")
    public String toIndex(Model model){
        model.addAttribute("msg","Hello,Shiro!!!");
        return "index";
    }

    @RequestMapping("/login")
    public String toLogin(){
        return "/user/login";
    }

    @RequestMapping("/logout")
    public String logout(){
        Subject user = SecurityUtils.getSubject();
        user.logout();
        return "index";
    }

    @RequestMapping("/toAuthc")
    public String toAuthc( String username, String userpwd, Model model){

        //获取当前用户对象
        Subject user = SecurityUtils.getSubject();
        //封装用户登录数据
        UsernamePasswordToken token=new UsernamePasswordToken(username,userpwd);

        try {
            user.login(token);

            //设置登录状态
            Session session = user.getSession();
            session.setAttribute("loginuser", true);

            return "index";
        }catch (UnknownAccountException e){
            //用户名不存在
            model.addAttribute("msg","用户名不存在！");
            return "/user/login";
        }catch (IncorrectCredentialsException e){
            //密码错误
            model.addAttribute("msg","密码错误！");
            return "/user/login";
        }

    }

    @RequestMapping("/user/add")
    public String userAdd(){
        return "/user/add";
    }

    @RequestMapping("/unauth")
    @ResponseBody
    public String unAuthorized(){
        return "未经授权，无法访问此页面";
    }
}
